package com.example.cgpsys.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.cgpsys.beans.Cart;
import com.example.cgpsys.beans.Order;
import com.example.cgpsys.beans.Result;
import com.example.cgpsys.dao.CartDao;
import com.example.cgpsys.dao.OrderDao;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/cart")
@RestController
public class CartController {

    private final CartDao cartDao;

    private final OrderDao orderDao;

    public CartController(CartDao cartDao, OrderDao orderDao) {
        this.cartDao = cartDao;
        this.orderDao = orderDao;
    }

    @GetMapping("/getList")
    public Result loadList(String username) {
        QueryWrapper<Cart> cartQueryWrapper = new QueryWrapper<>();
        cartQueryWrapper.eq("username",username);
        List<Cart> cartList = cartDao.selectList(cartQueryWrapper);
        for(Cart cart:cartList){
            QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
            orderQueryWrapper.eq("name",cart.getName());
            Integer num = orderDao.selectCount(orderQueryWrapper);
            cart.setPeoples(num);
        }
        return Result.success(cartList);
    }

    @GetMapping("/delete")
    public Result deleteCart(Integer id) {
        cartDao.deleteById(id);
        return Result.success();
    }

    @PostMapping("/addCart")
    public Result addCart(@RequestBody Cart cart) {
        QueryWrapper<Cart> cartQueryWrapper = new QueryWrapper<>();
        cartQueryWrapper.eq("name",cart.getName());
        cartQueryWrapper.eq("username",cart.getUsername());
        Cart selectOne = cartDao.selectOne(cartQueryWrapper);
        if (selectOne != null) {
            return Result.error("请勿重复加入购物车");
        }
        cartDao.insert(cart);
        return Result.success();
    }
}
